package XMFramework.Core.Internal
{
	import GTweener.TweenLite;
	
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	
	public class SDownloader
	{
		private var targetURL:String;
		private var loader : URLLoader;
		
		private var isDownloadSuccess:Boolean	=	false;
		private var onLoadSuccessFunc:Function;
		private var onStepLoadFunc:Function;
		
		public function SDownloader( url:String )
		{
			targetURL	=	url;
		}
		
		public function get isSuccess():Boolean
		{
			return isDownloadSuccess;
		}
		
		public function get URL():String
		{
			return targetURL;
		}
		
		public function download( loadSuccess:Function, stepLoad:Function=null, dataFormat:String=URLLoaderDataFormat.TEXT ):void
		{
			onLoadSuccessFunc	=	loadSuccess;
			onStepLoadFunc		=	stepLoad;
			
			loader					=	new URLLoader();
			loader.dataFormat		=	dataFormat;	
			
			loader.addEventListener( Event.COMPLETE, onComplete, false, 0, false );
			loader.addEventListener( IOErrorEvent.IO_ERROR, onFault, false, 0, false );
			loader.addEventListener( SecurityErrorEvent.SECURITY_ERROR, onFault, false, 0, false );
			loader.addEventListener( ProgressEvent.PROGRESS, onStepLoadHadler, false, 0, false );
			loader.addEventListener( HTTPStatusEvent.HTTP_STATUS, onHttpStatus, false, 0, false );
			
			try 
			{
				loader.load( new URLRequest( targetURL ) );
			}
			catch( ex:* ) 
			{
				trace("SDownloader::download Unable to load requested document:" + targetURL);
				TweenLite.delayedCall( 1, download, [onLoadSuccessFunc, onStepLoadFunc], true );
			}
			
			trace( "SDownloader::download start: " + targetURL );
		}
		
		private function onStepLoadHadler( evt:Event ):void
		{
			if( onStepLoadFunc != null )
				onStepLoadFunc.call( null, evt );
		}
		
		private function onComplete( evt:Event ):void
		{
			trace("SDownloader::onComplete: " + targetURL);
			
			isDownloadSuccess	=	true;
			if( onLoadSuccessFunc != null )
				onLoadSuccessFunc.call( null, evt );
		}
		
		private function onHttpStatus(event:HTTPStatusEvent):void 
		{
			trace("SDownloader::onHttpStatus: " + event.status);
		}
		
		private function onFault( evt:Event ):void
		{			
			trace("SDownloader::onFault: " + targetURL);
			
			// Retry download swf file
			TweenLite.delayedCall( 1, download, [onLoadSuccessFunc, onStepLoadFunc], true );
		}
	}
}